from rest_framework.views import APIView
from rest_framework.response import Response
from home import models, ser
from django.core.cache import cache


# Create your views here.
class TopNav(APIView):
    def get(self, request):
        cachedata = cache.get('top')
        if cachedata:
            print(cachedata)
            return Response({"msg": "ok", "data": cachedata, "code": 200})
        else:
            top = models.Nav.objects.filter(is_delete=0, position=1).order_by('sort')
            topser = ser.NavSer(top, many=True)
            cache.set("top",topser.data,60*60*24)
            return Response({"msg": "ok", "data": topser.data, "code": 200})


class BottomNav(APIView):
    def get(self, request):
        cachedata = cache.get('bottom')
        if cachedata:
            print(cachedata)
            return Response({"msg": "ok", "data": cachedata, "code": 200})
        else:
            bottom = models.Nav.objects.filter(is_delete=0, position=0).order_by('sort')
            bottomser = ser.NavSer(bottom, many=True)
            cache.set("bottom", bottomser.data, 60 * 60 * 24)  # 失效时间
            return Response({"msg": "ok", "data": bottomser.data, "code": 200})


class Banner(APIView):
    def get(self, request):
        cachedata = cache.get('banner')
        if cachedata:
            print(cachedata)
            return Response({"msg": "ok", "data": cachedata, "code": 200})
        else:
            banner = models.Banner.objects.filter(is_delete=0).order_by('sort')
            bannerser = ser.BanSer(banner, many=True)
            # 将数据写到缓存中一份
            cache.set("banner", bannerser.data, 60 * 60 * 24)  # 失效时间
            return Response({"msg": "ok", "data": bannerser.data, "code": 200})
